package com.example.application4.adapter;

import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.application4.R;
import com.example.application4.pojo.Photo;

import java.util.List;

public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.ViewHolder> {
    private List<Photo> photoList;
    private Context context;

    public PhotoAdapter(Context context, List<Photo> photoList) {
        this.photoList = photoList;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 创建一个新的视图
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.photo_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // 检查位置是否有效，防止越界
        if (position < 0 || position >= photoList.size()) {
            return;
        }

        // 获取当前位置的 Photo 对象
        Photo photo = photoList.get(position);
        String imagePath = photo.getPhotoId();

        // 使用 Glide 加载图片，并添加错误处理
        Glide.with(holder.itemView.getContext())
                .load(imagePath)
                .diskCacheStrategy(DiskCacheStrategy.ALL) // 启用磁盘缓存
                .error(R.drawable.tb_netease) // 设置错误图片
                .into(holder.photoView);

        // 设置点击事件
        holder.itemView.setOnClickListener(view -> {
            try {
                showImageDialog(imagePath);
            } catch (Exception e) {
                Toast.makeText(context, "图片加载失败，请重试", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        // 返回列表的大小
        return photoList != null ? photoList.size() : 0;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView photoView;

        public ViewHolder(View view) {
            super(view);
            // 初始化视图
            photoView = view.findViewById(R.id.photo_view);
        }
    }

    private void showImageDialog(String imagePath) {
        // 创建 Dialog
        final Dialog dialog = new Dialog(context);
        dialog.setContentView(R.layout.dialog_image);

        // 找到 ImageView 并设置图片
        ImageView imageView = dialog.findViewById(R.id.photo_view);
        Glide.with(context)
                .load(imagePath)
                .diskCacheStrategy(DiskCacheStrategy.ALL) // 启用磁盘缓存
                .error(R.drawable.tb_netease) // 设置错误图片
                .into(imageView);

        dialog.show();
    }
}